package middlewares

import (
	"github.com/gin-gonic/gin"
	"net/http"
)

// 用来解决前后端跨域问题中，浏览器的options机制，也就是解决跨域限制

func Cors() gin.HandlerFunc {
	return func(c *gin.Context) {

		method := c.Request.Method

		// 对预检请求options进行处理，然后制定规则来定义对应的请求头！！！

		c.Header("Access-Control-Allow-Origin", "*")
		// 允许的头字段
		c.Header("Access-Control-Allow-Headers", "Content-Type, AccessToken, X-CSRF-Token, Authorization, Token,x -token")
		// 可以添加的方法
		c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT, PATCH")
		c.Header("Access-Control-Expose-Headers",
			"Content-Type, Content-Length, Accept, Access-control-Allow-Origin, Access-control-Allow-Headers")

		c.Header("Access-Control-Allow-Credentials", "true")

		if method == "OPTIONS" {
			c.AbortWithStatus(http.StatusNoContent)

		}
	}
}
